import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/config/global_configs.dart';
import 'package:ls_work/net/api/http_api.dart';
import 'package:ls_work/res/gaps.dart';
import 'package:ls_work/util/ext_utils.dart';
import 'package:ls_work/viewmodel/food/regular_week_menu_view_model.dart';

import '../../../message/message_config.dart';
import '../../../net/response/food/regular_week_menu_list_data.dart';
import '../../../net/response/food/scan_old_data.dart';
import '../../../net/response/food/week_menu_list_data.dart';
import '../../../res/colors.dart';
import '../../../ui/food/new_week/new_regular_week_submit_page.dart';
import '../../../util/image_utils.dart';
import '../../../widgets/select_item_widget.dart';

class NewRegularWeekMenuViewModel extends RegularWeekMenuViewModel {
  final String? siteId;
  final String? time;
  final String? orderModelType;
  final ScanOldData? oldData;
  final String? useType;

  NewRegularWeekMenuViewModel(BuildContext context,
      {this.siteId, this.time, this.orderModelType, this.oldData, this.useType})
      : super(context,
            siteId: siteId,
            time: time,
            orderModelType: orderModelType,
            oldData: oldData,
            useType: useType);

  var timeSelection = 0;
  var dateSelection = 0;
  RegularWeekMenuContent? selectTime;
  GoodsInfo? selectDate;

  @override
  Widget menuContent() {
    if (selectTime == null) {
      selectTime = listItems[timeSelection];
      selectDate = selectTime?.goodsInfo?[dateSelection];
    }
    getSelectItem();
    return Column(
      children: [
        Container(
          height: 10,
        ),
        SelectItemWidget(
          selectTime?.goodsInfo ?? [],
          itemBuilder: (context, item, index, selected) {
            var data = item as GoodsInfo;
            var date = getDate(data.weekDay??0);
            var weekFormat = [D];
            var dateFormat = [m, '月', d, '日'];
            return Column(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                CommonText(date.formatDateStr(format: weekFormat),
                    textColor: selected ? Colors.white : Colors.black),
                CommonText(date.formatDateStr(format: dateFormat),
                    textColor: selected ? Colors.white : Colors.grey[400]!,
                    textSize: 14.5)
              ],
            ).addToContainer(
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  color: selected ? Colours.foodSelectColor : Colors.white,
                  borderRadius: 6.borderRadius),
              padding: EdgeInsets.symmetric(horizontal: 22, vertical: 5),
            );
          },
          scrollDirection: Axis.horizontal,
          position: dateSelection,
          separatorBuilder: (context, index) {
            return Container(
              width: 10,
            );
          },
          padding: EdgeInsets.symmetric(horizontal: 16),
          onCallback: (index, data) {
            dateSelection = index;
            selectDate = data;
            notifyListeners();
          },
        ).addToContainer(width: double.infinity, height: 55),
        Container(
          height: 16,
        ),
        Row(
          children: [
            SelectItemWidget(
              listItems,
              position: timeSelection,
              itemBuilder: (context, item, index, selected) {
                return LeftTimeTypeItemWidget(item, selected);
              },
              onCallback: (index, data) {
                timeSelection = index;
                selectTime = data;
                selectDate = selectTime?.goodsInfo![dateSelection];
                notifyListeners();
              },
            ).addToContainer(
                width: 70, margin: EdgeInsets.symmetric(horizontal: 16)),
            ListView(
              children: (selectDate?.goodsList ?? []).map((e) {
                return itemMenuContent(e);
              }).toList(),
            ).setWeight(3),
            Container(
              width: 16,
            )
          ],
        ).setWeight(1),
        bottomPriceWidget()
      ],
    );
  }

  Widget itemMenuContent(GoodsList food){
    return Stack(
      children: [
        Stack(
          children: [
            ImageLoad(
              "${HttpApi.imageHead}${food.attachIds}",
              fit: BoxFit.cover,
              width: 90,
              height: 90,
              placeholder: ImageUtils.getImgPath("none"),
              errorImage: ImageUtils.getImgPath("none"),
            ),
            CommonText(food.goodsName).setLocation(left: 100, top: 4),
            CommonText("¥${food.price}", textColor: Colors.red)
                .setLocation(bottom: 4, left: 100),
            Row(
              children: [
                if ((food.number ?? 0) > 0)
                  Icon(
                    Icons.remove_circle_outline,
                    color: Colours.foodSelectColor,
                    size: 30,
                  ).onTap(() {
                    removeClick(selectDate!, food);
                  }),
                if ((food.number ?? 0) > 0)
                  CommonText("${food.number}").addToContainer(
                      margin: EdgeInsets.symmetric(horizontal: 15)),
                Icon(
                  Icons.add_circle_outline,
                  color: Colours.foodSelectColor,
                  size: 30,
                ).onTap(() {
                  addClick(food, selectDate!, selectTime!);
                })
              ],
            ).setLocation(bottom: 0, right: 0),
          ],
        ).addToContainer(
            width: double.infinity,
            padding:
            EdgeInsets.symmetric(horizontal: 10, vertical: 10),
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: 10.borderRadius)),
        if (!food.canSelect||food.isTake==1)
          Container(
            decoration: BoxDecoration(
                color: Colors.grey.withAlpha(90),
                borderRadius: 10.borderRadius),
            width: double.infinity,
          ).onTap(() {
            if(!food.canSelect){
              showToast(food.canSelectRemark??"改餐不可点");
              return;
            }
            if(food.isTake==1){
              showToast("该餐已取餐");
              return;
            }
          }).setLocation(top: 0, bottom: 0, left: 0, right: 0)
      ],
    ).addToContainer(
      margin: EdgeInsets.only(bottom: 10),
    );
  }

  Widget bottomPriceWidget({bool clickShopcar = true}) {
    return Stack(
      children: [
        Image.asset(
          ImageUtils.getImgPath("food/shop_car"),
          width: 40,
          height: 40,
          color:
              selectedMealList.isEmpty ? Colors.black : Colours.foodSelectColor,
        ).onTap(() {
          if (selectedMealList.isEmpty) {
            return;
          }
          if (!clickShopcar) {
            Go().pop();
            return;
          }
          showSelectBottom();
        }).setLocation(top: 0, bottom: 0, left: 16),
        if (selectedMealList.isNotEmpty)
          CommonText("${selectedMealList.length}",
                  textColor: Colors.white, textSize: 14)
              .addToContainer(
                  decoration: BoxDecoration(
                      color: Colors.red, borderRadius: 20.borderRadius),
                  alignment: Alignment.center,
                  constraints: BoxConstraints(minHeight: 20, minWidth: 20))
              .setLocation(left: 44, top: 8),
        (GlobalConfigs.showPayPrice?Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            CommonText("¥", textSize: 16),
            CommonText((totalPrice.d - oldPrice.d).toStringOrNull(), textSize: 20)
          ],
        ):CommonText("")).setLocation(top: 0, bottom: 0, left: 70),
        TextButton(
          onPressed: () {
            if (!clickShopcar) {
              Go().pop();
              return;
            }
            Go().push(NewRegularWeekSubmitPage(
              menuData: menuData!,
              oldId: oldData!.selectOldId.toString(),
              sitId: siteId!,
              time: time!,
              orderModelType: orderModelType!,
              useType: useType!,
            ));
          },
          child: CommonText('去结算', textColor: Colors.white),
          style: ButtonStyle(
              backgroundColor: WidgetStateProperty.all(
                  selectedMealList.isEmpty
                      ? Colors.grey
                      : Colours.foodSelectColor),
              shape: WidgetStateProperty.all(StadiumBorder()),
              fixedSize: WidgetStateProperty.all(Size(90, 40))),
        )
            .addToContainer(alignment: Alignment.center)
            .setLocation(right: 16, top: 0, bottom: 0)
      ],
    ).addToContainer(width: double.infinity, height: 65, color: Colors.white);
  }

  ///点击-
  void removeClick(GoodsInfo date, GoodsList food) {
    food.number??=0;
    food.number = food.number!-1;
    if (food.number! <= 0) {
      food.selected = false;
      food.number = 0;
      food.status = 0;
      date.selectItems.remove(food);
    }
    getSelectItem();
    notifyListeners();
  }

  ///点击+
  void addClick(
    GoodsList food,
    GoodsInfo date,
    RegularWeekMenuContent time,
  ) {
    if(!food.canSelect){
      showToast(food.canSelectRemark??"改餐不可点");
      return;
    }
    if (hasLimitMoney) {
      num limitPrice = 0.0;
      if (time.timeSection == 1) {
        limitPrice = oldData?.limitData?.breakfastLimitMoney??0;
      }
      if (time.timeSection == 2) {
        limitPrice = oldData?.limitData?.lunchLimitMoney??0;
      }
      if (time.timeSection == 3) {
        limitPrice = oldData?.limitData?.dinnerLimitMoney??0;
      }

      if ((date.selectPrice() + (food.price??0)) > (limitPrice ?? 0)) {
        showToast("${time.timeStr}超过限额");
        print(date.selectPrice());
        return;
      }
        }
    food.selected = true;
    food.number = (food.number??0)+1;
    if ((food.status??0) == 0) {
      food.status = 1;
    }
    if (!date.selectItems.contains(food)) {
      date.selectItems.add(food);
    }
    getSelectItem();
    notifyListeners();
  }

  var selectedMealList = <GoodsInfo>[];
  var totalPrice = 0.0;
  var oldPrice = 0.0;

  void getSelectItem() {
    selectedMealList.clear();
    totalPrice = 0.0;
    oldPrice = 0.0;
    for (var item in listItems) {
      for (var date in item.goodsInfo ?? <GoodsInfo>[]) {

        for (var food in date.goodsList ?? <GoodsList>[]) {
          if (1 == food.oldStatus) {
            oldPrice += (food.price??0) * (food.oldNumber ?? 0);
          }
        }
        if (date.selectItems.isNotEmpty &&
            date.selectItems[0].canSelect &&
            1 != date.selectItems[0].isTake) {
          selectedMealList.add(date);

        }
        totalPrice += date.selectPrice();
      }
    }
    selectedMealList.sort((o1, o2) {
      return o1.weekDay!.compareTo(o2.weekDay!);
    });

    print("totalPrice===>${totalPrice}\noldPrice===>${oldPrice}");
  }

  void clearSelected() {
    if (selectedMealList.isEmpty) {
      return;
    }
    for (var item in selectedMealList) {
      for (var food in item.selectItems) {
        food.status = 0;
        food.number = 0;
      }
      item.selectItems.clear();
    }
    selectedMealList.clear();
    getSelectItem();
    notifyListeners();
  }

  void showSelectBottom() {
    showModalBottomSheet<void>(
        context: context,
        builder: (context) {
          return bottomContent();
        },
        isScrollControlled: true,
        constraints: selectedMealList.length >= 3
            ? BoxConstraints(
                maxHeight: MediaQuery.of(context).size.height * 0.7)
            : null);
  }

  Widget bottomContent() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          children: [
            CommonText('已选商品').setWeight(1),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Icon(
                  Icons.delete_outline,
                  color: Colors.grey[800],
                  size: 18,
                ),
                CommonText('清空', textSize: 14, textColor: Colors.grey[800]!)
              ],
            ).onTap(() {
              clearSelected();
              notifyListeners();
              Go().pop();
            })
          ],
        ).addToContainer(
            margin: EdgeInsets.symmetric(horizontal: 16, vertical: 16)),
        selectedMealList.length >= 3
            ? ListView.separated(
                padding: EdgeInsets.symmetric(horizontal: 16),
                itemBuilder: (context, index) {
                  var item = selectedMealList[index];
                  return selectMealItem(item);
                },
                separatorBuilder: (context, index) {
                  return Gaps.dividerLine;
                },
                itemCount: selectedMealList.length,
              ).setWeight(1)
            : ListView.separated(
                padding: EdgeInsets.symmetric(horizontal: 16),
                shrinkWrap: true,
                itemBuilder: (context, index) {
                  var item = selectedMealList[index];
                  return selectMealItem(item);
                },
                separatorBuilder: (context, index) {
                  return Gaps.dividerLine;
                },
                physics: NeverScrollableScrollPhysics(),
                itemCount: selectedMealList.length,
              ),
        bottomPriceWidget(clickShopcar: false)
      ],
    );
  }

  Widget selectMealItem(GoodsInfo info) {
    var paidList =
        (info.goodsList??[]).where((element) => element.oldStatus == 1).toList();
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 8,
        ),
        Row(
          children: [
            CommonText(
                    "${getDateValue(info.weekDay??0)?.toDateStr([
                          'm',
                          '月',
                          'd',
                          '日'
                        ])}  ${info.timeTypeId?.timeTypeStr()}",
                    textSize: 17,
                    textColor: Colors.grey[700]!,
                    fontWeight: FontWeight.bold)
                .setWeight(1),
            CommonText("¥${info.selectPrice() - info.paidPrice()}",
                textSize: 17, textColor: Colors.red),
          ],
        ),
        Container(
          height: 15,
        ),
        CommonText(
            info.selectItems.map((e) => "${e.goodsName}x${e.number}").join("、"),
            textColor: Colors.grey[800]!,
            textSize: 17),
        Container(
          height: 15,
        ),
        if (paidList.isNotEmpty) ...[
          CommonText(
            '已结算',
            textColor: Colors.grey,
          ),
          Container(
            height: 15,
          ),
          ...paidList
              .map((e) => Row(
                    children: [
                      Container(
                        width: 40,
                      ),
                      CommonText(e.goodsName, textColor: Colors.grey)
                          .setWeight(2),
                      CommonText("x${e.oldNumber}",
                              textColor: Colors.grey,
                              textAlign: TextAlign.center)
                          .setWeight(1),
                      CommonText("¥${e.price}",
                              textColor: Colors.grey, textAlign: TextAlign.end)
                          .setWeight(1),
                    ],
                  ))
              .toList(),
          Container(
            height: 15,
          ),
        ]
      ],
    );
  }

  @override
  void receiveMessage(SendMessageEvent event) {
    super.receiveMessage(event);
    if(event.msgCode==MessageConfig.PAY_FOOD_SUCCESS){
      finish();
    }
  }
}

Widget LeftTimeTypeItemWidget(RegularWeekMenuContent e, bool selected) {
  return Column(
    children: [
      titleImage(e.timeSection.toString(), selected),
      Container(
        height: 8,
      ),
      CommonText(e.timeStr, textColor: Colors.grey[700]!)
    ],
  ).addToContainer(margin: EdgeInsets.only(bottom: 10));
}
